package hhq.demo.wechart.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.stereotype.Repository;

import hhq.demo.wechart.popj.ChartMess; 

@Repository
public class MessDao {
    static final int EXP_TIME = 1000*60*5; // 过期 时间 ms
    static List<ChartMess> all_mess = new ArrayList<>(); //存放所有消息 按照时间顺序
    static Map<String, byte[]> data_map = new TreeMap<>();  // 存放所有二进制数据

    public void put_byte(String key, byte[] val){
        data_map.put(key, val);
    }

    public byte[] get_byte(String key){
        if( data_map.containsKey(key) ){
            return data_map.get(key);
        }else{
            return null;
        }
    }

    // 插入一条信息
    public void insertOne(ChartMess m){
         all_mess.add(m);
    }

    // 查询某个人的收件箱
    public List<ChartMess> queryMessByUid(String uid){
        List<ChartMess> res = new LinkedList<>();
        Iterator<ChartMess> it = all_mess.iterator();

        // 清理过期的
        while(it.hasNext()){
            ChartMess m = it.next();
            long nowTime  = System.currentTimeMillis();
            if( nowTime - m.getTime() > EXP_TIME  ){
                data_map.remove(m.getData());
                it.remove(); 
            }else{
                break;
            }
        } 

       it = all_mess.iterator(); 
        while(it.hasNext()){
            ChartMess m = it.next();
            if(m.getToUID().equals(uid)){
                res.add(m);
            }
        } 
        return res;
    } 
}
